//
//  DataChe.m
//  文印室
//
//  Created by KL on 17/2/22.
//  Copyright © 2017年 KM. All rights reserved.
//

#import "DataChe.h"

@implementation DataChe

+ (void)loginWithName:(NSString *)name WithPassword:(NSString *)password complete:(void (^)(NSDictionary *))handle
{
    NSMutableString *str = [NSMutableString stringWithFormat:@"http://a.xl18z.cn/api/login?"];
    NSDictionary *dic = @{
                          @"name":name,
                          @"password":password
                          };
    for (NSString *key in dic) {
        [str appendFormat:@"%@=%@&",key,dic[key]];
    }
    NSString *str2 = [str substringToIndex:str.length-1];
    //NSLog(@"%@",str2);
    [self getWithParam:str2 complete:^(NSDictionary *d) {
        handle(d);
    }];
}

+ (void)getWithParam:(NSString *)str complete:(void (^)(NSDictionary *))handle
{
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 获取到数据了。
        NSString *text = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
        NSLog(@"%@",text);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                handle(dict);
            });
    }];
    [task resume];

}
@end
